import {ExclamationCircleOutlined, PlusOutlined, RightOutlined} from '@ant-design/icons';
import {Badge, Button, Divider, Drawer, Form, Input, InputNumber, message, Modal, Select, Tag, Switch} from 'antd';
import React, {useEffect, useRef, useState} from 'react';
import {PageContainer} from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import ProDescriptions from '@ant-design/pro-descriptions';
import WarehouseForm from './components/WarehouseForm';
import {
  addWarehouse,
  disableWarehouse,
  enableWarehouse,
  queryWarehouse,
  queryWarehouseMaterial,
  queryWarehouseMould,
  queryWarehouseProduct,
  removeWarehouse,
  updateWarehouse
} from '@/services/warehouse';
import {
  addMaintenance,
  queryAccount,
  queryEqp,
  queryMaintenance,
  removeMaintenance, startMaintenance,
  updateMaintenance
} from "@/services/system";
import AccountForm from "@/pages/system/account-manage/components/AccountForm";
import moment from "moment/moment";

const initRecord = {
  id: '',
  maintenceName: '',
  enable: '',
  cycle: '',
  advanceNoticeTime: '',
  remark: ''
}

const TableList = () => {
  const [createModalVisible, handleModalVisible] = useState(false);
  const [selectedRow, handleSelectedRow] = useState({});
  const [detailVisible, handleDetailVisible] = useState(false);
  const [activekey, setActiveKey] = useState('tab1');
  const [detailWarehouse, handleDetailWarehouse] = useState({})
  const [formTitle, setFormTitle] = useState('新增保养');
  const actionRef = useRef();
  const detailRef = useRef();
  const [formRef] = Form.useForm();
  const [row, setRow] = useState();
  const [selectedRowsState, setSelectedRows] = useState([]);
  const [warehouseInAdmData, setWarehouseInAdmData] = useState([]);
  const [warehouseOutAdmData, setWarehouseOutAdmData] = useState([]);
  const [eqpData, setEqpData] = useState([]);
  const {Option} = Select;
  const handleUpdateModalVisible = (record) => {
    formRef.setFieldsValue({
      ...record
    })
    handleSelectedRow(record)
    setFormTitle('更新保养')
    handleModalVisible(true)
  }
  const handleCreateModalVisible = () => {
    formRef.setFieldsValue({
      ...initRecord
    })
    setFormTitle('新增保养')
    handleModalVisible(true)
  }
  const handleMaintenanceModalVisible = (record) => {
    handleSelectedRow(record)
    formRef.setFieldsValue({
      realTime: moment(new Date()).format('YYYY-MM-DD'),
      nextTime: record.nextTime
    });
    setFormTitle('开始保养')
    handleModalVisible(true)
  }

  const showDetailTable = (warehouse) => {
    handleDetailVisible(true)
    handleDetailWarehouse(warehouse)
  }

  const handleEnable = async (fields) => {

    try {
      if (fields.warehouseStatus === 1) {
        await disableWarehouse({...fields});
      } else {
        await enableWarehouse({...fields});
      }
      if (actionRef.current) {
        actionRef.current.reload();
      }
      return true;
    } catch (error) {

      return false;
    }
  };

  const handleAdd = async (fields) => {
    const hide = message.loading('正在添加');
    fields.enable = fields.enable? 1: 0
    try {
      await addMaintenance({...fields});
      hide();
      message.success('添加成功');
      return true;
    } catch (error) {
      hide();
      message.error('添加失败请重试！');
      return false;
    }
  };

  const handleUpdate = async (fields) => {
    const hide = message.loading('正在配置');
    fields.enable = fields.enable? 1: 0
    try {
      await updateMaintenance({...fields, id: selectedRow.id});
      hide();
      message.success('配置成功');
      return true;
    } catch (error) {
      hide();
      message.error('配置失败请重试！');
      return false;
    }
  };

  const handleStartMaintenace = async (fields) => {
    const hide = message.loading('开始保养');
    try {
      await startMaintenance({
        maintenceId: selectedRow.id,
        planTime: selectedRow.nextTime,
        realTime: fields.realTime,
        remark: fields.remark,
        cycle: selectedRow.cycle,
        maintenceCount: selectedRow.finishedCount + 1
      });
      hide();
      message.success('保养成功');
      return true;
    } catch (error) {
      hide();
      message.error('保养失败请重试！');
      return false;
    }
  };

  const handleRemove = async (selectedRows) => {
    const hide = message.loading('正在删除');
    if (!selectedRows) return true;

    try {
      await removeMaintenance({...selectedRows});
      hide();
      message.success('删除成功，即将刷新');
      return true;
    } catch (error) {
      hide();
      message.error('删除失败，请重试');
      return false;
    }
  };

  const deleteConfig = (record) => {
    Modal.confirm({
      title: '注意',
      icon: <ExclamationCircleOutlined/>,
      content: `是否要删除名称为 【${record.maintenceName} 】的保养？`,
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        handleRemove(record);
        if (actionRef.current) {
          actionRef.current.reload();
        }
      }
    });
  };

  useEffect(() => {
    queryEqp({
      current: 1,
      size: 99999,
    }).then(res => {
      setEqpData(res.result.records)
    })

  }, [])


  const columns = [
    {
      title: '序号',
      dataIndex: 'key',
      hideInForm: true,
      hideInSearch: true,
      render: (text, record, index, action) => {
        return `${index + 1}`
      }
    },
    {
      title: '保养名称',
      dataIndex: 'maintenceName',
      formItemProps: {
        rules: [
          {
            max: 32,
            message: '保养名称最大长度为32'
          },
          {
            whitespace: true,
            message: '请不要输入空格'
          },
          {
            required: true,
            message: '保养名称是必填项'
          }
        ],
      },
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return <Input maxLength={11} placeholder={'请输入保养名称'} disabled={formTitle === '更新保养' && createModalVisible}/>;
      }
    },
    {
      title: '设备ID',
      dataIndex: 'equipmentId',
      hideInSearch: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '设备ID是必填项'
          }
        ],
      },
      render: (text, record, index, action) => {
        return record.equipmentName + '[' + record.equipmentId + ']'
      },
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return <Select disabled={formTitle !== '新增保养'}>
          {
            eqpData.map(item => {
              return <Option value={item.id} key={item.id}>{item.equipmentName}</Option>
            })
          }
        </Select>
      }
    },
    {
      title: '保养周期',
      dataIndex: 'cycle',
      hideInSearch: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '保养周期是必填项'
          }
        ],
      },
      render: (text, record, index, action) => {
        return text + '天'
      },
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return <InputNumber addonAfter="天"/>;
      }
    },
    // {
    //   title: '提前通知时间',
    //   dataIndex: 'advanceNoticeTime',
    //   hideInSearch: true,
    //   formItemProps: {
    //     rules: [
    //       {
    //         required: true,
    //         message: '提前通知时间是必填项'
    //       }
    //     ],
    //   },
    //   render: (text, record, index, action) => {
    //     return text + '天'
    //   },
    //   renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
    //     return <InputNumber addonAfter="天"/>;
    //   }
    // },
    {
      title: '下次保养日期',
      dataIndex: 'nextTime',
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '已完成保养次数',
      dataIndex: 'finishedCount',
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '当前周期保养状态',
      dataIndex: 'currentCycleStatus',
      hideInSearch: true,
      hideInForm: true,
      render: (text, record) => {
        return <Tag color={text === 1 ? 'green' : 'red'}>{text === 1 ? '待保养' : '已逾期'}</Tag>;
      }
    },
    {
      title: '启用状态',
      dataIndex: 'enable',
      hideInSearch: true,
      render: (text, record) => {
        return <Tag color={text === 1 ? 'green' : 'red'}>{text === 1 ? '启用' : '停用'}</Tag>;
      },
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return <Switch checkedChildren="启用" unCheckedChildren="停用" />
      }

    },
    {
      title: '创建人',
      dataIndex: 'createByName',
      hideInSearch: true,
      hideInForm: true
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      sorter: true,
      valueType: 'dateTime',
      hideInSearch: true,
      hideInForm: true
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a onClick={() => setRow(record)}>
          详情
        </a>,
        <Divider type="vertical"/>,
        <a onClick={() => handleUpdateModalVisible(record)}>修改</a>,
        record.enable ===1 ?<Divider type="vertical"/> : <></>,
        record.enable ===1 ?<a onClick={() => handleMaintenanceModalVisible(record)}>保养</a> : <></>,
        <Divider type="vertical"/>,
        <a onClick={() => deleteConfig(record)}>删除</a>,
      ],
    },
  ];

  const maintenanceColumns = [
    {
      title: '计划保养日期',
      dataIndex: 'nextTime',
      hideInSearch: true,
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return <Input disabled={true} />;
      }
    },
    {
      title: '当前保养日期',
      dataIndex: 'realTime',
      hideInSearch: true,
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return <Input disabled={true} />;
      }
    },
    {
      title: '备注',
      dataIndex: 'remark',
      hideInSearch: true,
    },
  ];


  const renderBadge = (count, active = false) => {
    return (
      <Badge
        style={{
          marginTop: -2,
          marginLeft: 4,
          color: active ? '#1890FF' : '#999',
          backgroundColor: active ? '#E6F7FF' : '#eee',
        }}
      />
    );
  };

  return (
    <PageContainer>
      <ProTable
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button type="primary" onClick={() => handleCreateModalVisible()}>
            <PlusOutlined/> 新建保养
          </Button>,
        ]}
        request={async (params, sorter, filter) => {
          const param = {...params, size: params.pageSize};
          const res = await queryMaintenance(param)
          return {
            data: res.result.records,
            success: true,
            total: res.result.total
          }
        }}
        columns={columns}
      />
      <AccountForm title={formTitle} onCancel={() => handleModalVisible(false)} modalVisible={createModalVisible}>
        <ProTable
          onSubmit={async (value) => {
            const success = formTitle === '新增保养' ? await handleAdd(value) : (formTitle === '开始保养' ? await handleStartMaintenace(value) : await handleUpdate(value));

            if (success) {
              handleModalVisible(false);

              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          form={{
            form: formRef,
            layout: 'horizontal',
            labelAlign: 'left'
          }}
          rowKey="key"
          type="form"
          columns={ formTitle === '开始保养' ? maintenanceColumns : columns}
        />
      </AccountForm>

      <Drawer
        width={600}
        visible={!!row}
        onClose={() => {
          setRow(undefined);
        }}
        closable={false}
      >
        {row?.maintenceName && (
          <ProDescriptions
            column={2}
            title={row?.maintenceName}
            request={async () => ({
              data: row || {},
            })}
            params={{
              id: row?.maintenceName,
            }}
            columns={columns}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

export default TableList;
